<template>
  <div>
    <div v-if="requireReview">
      <el-form ref="postForm" :model="postForm" label-position="left" label-width="100px">
        <el-form-item label="批阅类型">
          <el-radio-group v-model="postForm.assignType" size="small">
            <el-radio :label="1">
              实时批阅
            </el-radio>
            <el-radio :label="2">
              统一批阅
            </el-radio>
          </el-radio-group>
          <el-alert v-if="postForm.assignType===1" title="学员交卷后，系统立即派发阅卷任务" type="info" />
          <el-alert v-if="postForm.assignType===2" title="在考试结束后，集中在设定的阅卷时间内进行批阅" type="info" />
        </el-form-item>
        <el-form-item label="审阅配置">
          <el-radio-group v-model="postForm.auditType" size="small">
            <el-radio :label="0">
              无需审阅
            </el-radio>
            <el-radio :label="1">
              阅卷管理员审阅
            </el-radio>
          </el-radio-group>
          <el-alert v-if="postForm.auditType===0" title="需人工批阅的试卷在阅卷后出分，无需批阅的直接出分" type="info" />
          <el-alert v-if="postForm.auditType===1" title="需要在阅卷管理员审阅通过后出分" type="info" />
        </el-form-item>
        <el-form-item label="阅卷管理员">
          <el-tag v-if="postForm.manager" style="margin-right: 8px;">
            {{ postForm.manager_dictText }}
          </el-tag>
          <el-button size="mini" type="danger" icon="el-icon-edit" @click="showAddUser(-1)">
            选择人员
          </el-button>
        </el-form-item>
        <el-form-item label="隐藏学员姓名">
          <el-checkbox v-model="postForm.hideName" />
        </el-form-item>
        <el-form-item v-if="postForm.assignType===2" label="阅卷时间">
          <date-time-picker :start-time.sync="postForm.startTime" :end-time.sync="postForm.endTime" :min-date="endTime" />
        </el-form-item>
        <el-form-item label="阅卷方式">
          <el-radio-group v-model="postForm.reviewType" size="small">
            <el-radio label="1">
              整卷批阅
            </el-radio>
            <el-radio :disabled="joinType==='rand'" label="2">
              按大题指派阅卷人
            </el-radio>
            <el-radio :disabled="joinType==='rand'" label="100">
              按小题指派阅卷人
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="postForm.reviewType==='1'" label="阅卷人员">
          <el-radio-group v-model="postForm.ruleList[0].authType">
            <el-radio :label="1">
              部门阅卷老师
            </el-radio>
            <el-radio :label="2">
              指定人员
            </el-radio>
          </el-radio-group>
          <el-alert v-if="postForm.ruleList[0].authType===1" title="由各个部门的阅卷老师批阅自己所在部门的学员试卷" type="info" />
          <div v-if="postForm.ruleList[0].authType===2">
            <el-tag v-for="user in postForm.ruleList[0].userList" :key="user.id" style="margin-right: 8px; margin-bottom: 8px" closable @close="removeUser(postForm.ruleList[0].userList, user.id)">
              {{ user.realName }}
            </el-tag> <el-button size="mini" type="primary" icon="el-icon-plus" @click="showAddUser(0)">
              添加人员
            </el-button> <el-button v-if="postForm.ruleList[0].userList && postForm.ruleList[0].userList.length > 0" size="mini" type="danger" icon="el-icon-delete" @click="clearAllUser(0)">
              移除所有
            </el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="postForm.ruleList[0].authType !== 3" label="分工策略">
          <el-radio-group v-model="postForm.workType" size="small">
            <el-radio :disabled="postForm.reviewType!=='1'" label="1">
              自由批阅
            </el-radio>
            <el-radio :disabled="postForm.assignType===1" label="2">
              平均分配
            </el-radio>
          </el-radio-group>
          <el-alert v-if="postForm.workType==='1'" title="有权限的人员进入系统后，可自由批阅试卷，不由系统分配工作量" type="info" />
          <el-alert v-if="postForm.workType==='2'" title="由系统根据阅卷人员和考试人员进行平均分配工作量，必须配置阅卷时间，集中在考完后的某个时间段进行批阅" type="info" />
        </el-form-item>
        <el-form-item v-if="postForm.reviewType!=='1'" label="策略明细">
          <el-card v-for="(item,index) in postForm.ruleList" :key="item.refId" style="margin-bottom: 20px">
            <div slot="header" class="clearfix">
              <span>{{ item.title }}</span>
            </div>
            <div>
              <el-radio-group v-model="item.authType">
                <el-radio :label="1">
                  部门阅卷老师
                </el-radio>
                <el-radio :label="2">
                  指定人员
                </el-radio>
              </el-radio-group>
            </div>
            <div v-if="item.authType===2">
              <el-tag v-for="user in item.userList" :key="user.id" style="margin-right: 8px; margin-bottom: 8px" closable @close="removeUser(item.userList, user.id)">
                {{ user.realName }}
              </el-tag> <el-button size="mini" type="primary" icon="el-icon-plus" @click="showAddUser(index)">
                添加人员
              </el-button> <el-button v-if="item.userList && item.userList.length > 0" size="mini" type="danger" icon="el-icon-delete" @click="clearAllUser(index)">
                移除所有
              </el-button>
            </div>
          </el-card>
        </el-form-item>
      </el-form> <user-select-dialog :dialog-show.sync="dialogVisible" :excludes="excludes" :user-type="2" :roles="['reviewer']" @select="userSelected" />
    </div>
    <div v-else>
      <el-empty description=" ">
        <div style="color: #909399; font-size: 14px; text-align: left; line-height: 28px">
          <div style="font-weight: 700">
            当前考试无需配置阅卷功能，所有题目都由系统自动批阅！
          </div>
          <div>
            1、关联的试卷不含主观题。
          </div>
          <div>
            2、试卷包含主观题，但主观题已配置按关键词自动给分。
          </div>
        </div>
      </el-empty>
    </div>
  </div>
</template>
<script>
import { listTmplGroup, listTmplQu } from '@/api/exam/exam'
import UserSelectDialog from '@/views/admin/sys/user/components/UserSelectDialog.vue'
import DateTimePicker from '@/components/DateTimePicker/index.vue'
import UserSelect from '@/components/UserSelect/index.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'ReviewSettings',
  components: { UserSelect, DateTimePicker, UserSelectDialog },
  props: {
    tmplId: String,
    joinType: String,
    requireReview: Boolean,
    endTime: Date,
    value: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },

  data() {
    return {
      dialogVisible: false,
      excludes: [],
      postForm: {
        assignType: 2,
        auditType: 0,
        // 隐藏名称
        hideName: true,
        // 阅卷方式
        reviewType: '1',
        // 分工策略
        workType: '1',
        ruleList: [
          {
            authType: 1,
            userList: []
          }
        ]
      },
      manager: null,
      ruleIndex: 0
    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },
  watch: {
    // 检测查询变化
    value: {
      handler() {
        this.fillData()
      }
    },
    // 检测查询变化
    postForm: {
      handler(val) {
        this.$emit('input', val)
      },
      deep: true
    },
    'postForm.reviewType': {
      handler(val) {
        if (val === '1') {
          this.postForm.ruleList = [
            {
              authType: 1,
              userList: []
            }
          ]
        }
        if (val === '2') {
          this.postForm.workType = '2'
          this.fetchGroupList()
        }

        if (val === '100') {
          this.postForm.workType = '2'
          this.fetchQuList()
        }
      }
    },
    'postForm.authType': {
      handler(val) {
        if (val === 1) {
          if (!this.postForm.ruleList) {
            this.$set(this.postForm, 'ruleList', [])
          } else {
            this.postForm.ruleList = []
          }
        }
      }
    },
    requireReview: {
      handler() {
        this.fillData()
      }
    }
  },
  created() {
    this.fillData()
  },
  methods: {


    // 数据回填
    fillData() {
      // 无需阅卷的
      if (!this.requireReview) {
        return
      }

      if (this.value && this.value.id) {
        this.postForm = this.value

        // 默认规则
        if (this.postForm.ruleList.length === 0) {
          this.postForm.ruleList = [{ authType: 1, userList: [] }]
        }
        if (this.postForm.startTime && this.postForm.endTime) {
          this.dateRange = [this.postForm.startTime, this.postForm.endTime]
        }
      }
    },

    // 根据试卷模板加载全部大题
    fetchGroupList() {
      listTmplGroup(this.tmplId).then(res => {
        const list = res.data
        const results = []
        if (list && list.length > 0) {
          for (let i = 0; i<list.length; i++) {
            results.push({ title: list[i].title, refId: list[i].id, authType: 1, userList: [] })
          }
        }
        this.mergeRules(results)
      })
    },

    // 根据试卷模板加载试卷列表 maybe主观题？
    fetchQuList() {
      listTmplQu(this.tmplId).then(res => {
        const list = res.data
        const results = []
        if (list && list.length > 0) {
          for (let i = 0; i<list.length; i++) {
            results.push({ title: list[i].content, refId: list[i].quId, authType: 1, userList: [] })
          }
        }
        this.mergeRules(results)
      })
    },

    // 合并数据
    mergeRules(results) {
      if (!this.postForm.ruleList || this.postForm.ruleList.length === 0) {
        this.postForm.ruleList = results
        return
      }
      const list = []
      for (let i = 0; i<results.length; i++) {
        const aa = results[i]
        for (let j = 0; j<this.postForm.ruleList.length; j++) {
          const bb = this.postForm.ruleList[j]
          if (bb.refId === aa.refId) {
            aa.authType = bb.authType
            aa.userList = bb.userList || []
            aa.reviewer = bb.reviewer || ''
            break
          }
        }
        list.push(aa)
      }
      this.postForm.ruleList = list
    },

    // 移除单个用户
    removeUser(list, id) {
      for (let i = list.length - 1; i >= 0; i--) {
        if (list[i].id === id) {
          list.splice(i, 1)
        }
      }
      this.syncExcludes()
    },

    // 添加到用户列表
    userSelected(ids, objs) {
      // 选择管理员
      if (this.ruleIndex === -1) {
        if (objs && objs.length > 0) {
          const last = objs.pop()
          this.postForm.manager = last.id
          this.postForm.manager_dictText = last.realName
        }
        return
      }


      const rule = this.postForm.ruleList[this.ruleIndex]
      if (!rule.userList) {
        this.$set(rule, 'userList', [])
      }
      // 找到对应的数据
      let list = this.postForm.ruleList[this.ruleIndex].userList
      if (!list) {
        list = []
      }
      if (objs && objs.length > 0) {
        for (let i = 0; i<objs.length; i++) {
          list.push(objs[i])
        }
      }
      // 刷新页面
      this.$forceUpdate()
    },

    // 打开用户选择框
    async showAddUser(index) {
      // 构建排除用户
      await this.syncExcludes(index)

      this.ruleIndex = index
      this.dialogVisible = true
    },

    // 移除自定义用户
    clearAllUser(index) {
      // 整卷批阅
      if (this.ruleIndex === -1) {
        this.postForm.userList = []
      } else {
        // 细分批阅
        this.postForm.ruleList[index].userList = []
      }
    },
    syncExcludes(index) {
      // 排除已选定用户
      const ids = []
      const rule = this.postForm.ruleList[index]
      if (rule && rule.userList && rule.userList.length>0) {
        for (let i = 0; i<rule.userList.length; i++) {
          ids.push(rule.userList[i].id)
        }
      }
      this.excludes = ids
    }
  }
}
</script>
<style scoped>
::v-deep .el-card__header{
  padding: 8px 15px;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
}

::v-deep .el-alert__content{
  line-height: 20px;
  padding: 0;
}

</style>
